import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { stripesConnect,IfPermission } from '@folio/stripes/core';
import { FormattedMessage, injectIntl } from 'react-intl';
import { get } from 'lodash';
import {
  StripesConnectedSource,

} from '@folio/stripes/smart-components';
import {
  Button,
  MultiColumnList,
  ButtonGroup
} from '@folio/stripes/components';
import SearchForm from '../../components/party-blacklist/search-form';
class List extends React.Component {
  static manifest = Object.freeze({
    id:{ initialValue: '' },
    recordId:{ initialValue: '' },
    blackListQuery: { initialValue: '{"punishmentRecordGroup":[{\"status\":\"1\"}]}' },
    resultCount: { initialValue: 10 },
    blackListRecords: {
      type: 'okapi',
      records: 'readerCreditRecordGroup',
      limitParam: 'limit',
      path: 'party/reader/credit/record',
      recordsRequired: '%{resultCount}',
      perRequest: 10,
      GET: {
        params: {
          query: '${blackListQuery}'
        }
      }
    },
    httpBlackListModifyInvoke: {
      type: 'okapi',
      accumulate: true,
      pk:'sdsi',
      path: 'party/reader/credit/record/modify/%{id}/and/%{recordId}',
       
    }
  });
    static propTypes = {
        stripes: PropTypes.shape({
          logger: PropTypes.object
        }).isRequired,
        resources: PropTypes.object,
        history:PropTypes.object,
        mutator: PropTypes.shape({
    
          auxiliaryQuery: PropTypes.string,
          equipmentRecords: PropTypes.shape({
            PUT: PropTypes.func.isRequired,
            POST: PropTypes.func.isRequired,
            GET: PropTypes.func.isRequired,
            DELETE: PropTypes.func.isRequired
          }),
       httpBlackListModifyInvoke:  
       PropTypes.shape({
      
      DELETE: PropTypes.func.isRequired
    })
        }).isRequired,
        toModel: PropTypes.func
      };

      constructor(props) {
        super(props);
        this.logger = props.stripes.logger;
        this.log = this.logger.log.bind(this.logger);
        this.state = {
          searchForm: {},
          editOpen: false,
          editParams: {},
   
        };
      }
      componentDidMount() {
        this.source = new StripesConnectedSource(this.props, this.logger);
      }
    
      componentDidUpdate() {
        this.source.update(this.props, 'blackListRecords');
      }
      moreData = () => {
        if (this.source) {
          this.source.fetchMore(10);
        }
      };
    search=({...formData})=>{
      const { mutator } = this.props;
       //{username: "123", barcode: "123", prisonTerm: "2020-10-01", createDate: "2020-10-01"}
      let query = '';
      let list = []
      let punishmentRecordGroup = []
      let punishmentRecord={
           status:'1'
      }
      let readerInfo = {

      }
      if(!!formData && !!formData.createDate){
         punishmentRecord.createDate = formData.createDate
      }
      punishmentRecordGroup.push(punishmentRecord);

      if(!!formData.username){
        readerInfo.name = formData.username
      }

      if(!!formData.barcode){
        readerInfo.barcode = formData.barcode;
      }
      let queryObject= {
        punishmentRecordGroup:JSON.stringify(punishmentRecordGroup)
      }
     
      if( readerInfo.name || readerInfo.barcode){
        queryObject.readerInfo=JSON.stringify(readerInfo)
      }
      let queryString = JSON.stringify(queryObject)
      
      // if(!!formData && !!formData.username){
      //    list.push(` readerInfo.name == *${formData.username}* `)
      // }
      // if(!!formData && !!formData.barcode){
      //   list.push(` readerInfo.barcode == *${formData.barcode}* `)  
      // }
      // if(!!formData && !!formData.prisonTerm){
      //   list.push(` punishmentRecordGroup == *"prisonTerm"*: *"${formData.prisonTerm}"* `)  
      // }
   
      // if(list.length >0){
      //     const queryParam=list.join(" and ").toString();
      //     query+= `(${queryParam})  and  punishmentRecordGroup == *"status"*: *"1"* sortby metadata.updatedDate/sort.descending  `;
      //     if(!!formData && !!formData.createDate){
      //       // list.push(` punishmentRecordGroup == *"createDate"*: *"${formData.createDate}"* `)    
      //       query += " && createDate="+formData.createDate;
      //     }
    
      // }else{
      //   query = ` punishmentRecordGroup == *"status"*: *"1"* sortby metadata.updatedDate/sort.descending `
      //   if(!!formData && !!formData.createDate){
      //     // list.push(` punishmentRecordGroup == *"createDate"*: *"${formData.createDate}"* `)    
      //     query += " && createDate="+formData.createDate;
      //   }
      // }

      mutator.blackListQuery.replace(queryString)
      if (this.source) {
        this.source.update(this.props, 'blackListRecords');
      }
    }
    delData=(item)=>{
       console.log(item)
       const { mutator } = this.props;
       mutator.id.replace(item.id)
       mutator.recordId.replace(item.punishmentRecordGroup[0].id);
       if(confirm('你确定要删除这条黑名单记录?')){
          mutator.httpBlackListModifyInvoke.DELETE(item)
       }
    }
    render() {
        const { resources, toModel } = this.props;
        if (this.source) {
          this.source.update(this.props, 'blackListRecords');
        }
        const totalCount = this.source ? this.source.totalCount() : 0;
        const dataList = get(resources, 'blackListRecords.records', []);

        const formatter = {
            serialNumber: (
              <FormattedMessage id="ui-party.loans.columns.serialNumber" />
            ),
            barcode: <FormattedMessage id="ui-party.loans.columns.party.blocklist.barcode" />,
            username: <FormattedMessage id="ui-party.loans.columns.readerName" />,
            mobilePhone: <FormattedMessage id="ui-party.loans.columns.party.blocklist.mobilePhone" />,
            createDate: <FormattedMessage id="ui-party.loans.columns.party.blocklist.createDate" />,
            foulDescription: <FormattedMessage id="ui-party.loans.columns.party.blocklist.foulDescription" />,
            prisonTerm: <FormattedMessage id="ui-party.loans.columns.party.blocklist.prisonTerm" />,
            edit: <FormattedMessage id="ui-party.loans.columns.operating.edit" />
          };
        
        return (
            <div style={{ width:'100%', height:'580px' }}>
             <SearchForm 
               onSubmit={this.search}
               add={()=>{
                }}
                toModel={toModel}
               ></SearchForm>
         
        <MultiColumnList
          autosize
          virtualize
          interactive={false}

          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          totalCount={totalCount}
          contentData={dataList}
          onNeedMoreData={this.moreData}
          columnMapping={formatter}
          columnWidths={{
            serialNumber: '5%',
            barcode: '13%',
            username: '10%',
            mobilePhone: '12%',
            createDate: '10%',
            foulDescription: '20%',
            prisonTerm: '15%',
            edit: '20%',
           
          }}
          visibleColumns={[
            'serialNumber',
            'barcode',
            'username',
            'mobilePhone',
            'createDate',
            'foulDescription',
            'prisonTerm',
            'edit'
          ]}
          formatter={{
          
            barcode: item =>[<span>{item.readerInfo.barcode}</span>],
            username: item =>[<span>{item.readerInfo.name}</span>],
            mobilePhone: item =>[<span>{item.readerInfo.mobilePhone}</span>],
            serialNumber: item => [<span>{item.rowIndex + 1}</span>],
            edit: item => [
              <ButtonGroup>
                <Button
                    onClick={() => {
                       toModel('/black/list/edit',{id:item.id,recordId:item.punishmentRecordGroup[0].id})
                    }}
                >
                  <FormattedMessage id={"ui-party.loans.columns.operating.edit"}/>
                </Button>
          
              <Button
                style={{ border: '1px solid #900', color: ' #900' }}

                onClick={() => {
                    this.delData(item);
                }}
              >
                 <FormattedMessage id={"ui-party.loans.columns.operating.remove"}/>
              </Button>
            
            </ButtonGroup>
            ],
            createDate: item =>{
              let date = (item.punishmentRecordGroup )[0].createDate;
              return <span>{date}</span>
            },
            foulDescription: item =>{
              let foulDescription = (item.punishmentRecordGroup )[0].foulDescription;
              return      <div
              title={foulDescription}
              style={{
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis'
              }}
             >
              {foulDescription}
            </div>
            },
            prisonTerm:  item =>{
              let prisonTerm = (item.punishmentRecordGroup )[0].prisonTerm;
              return <span>{prisonTerm}</span>
            },
          }}
        />
      </div>
        );
    }
}

 

export default injectIntl(stripesConnect(List))
